import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.Timer;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

import util.CustomFormatter;
import util.Vector;

import environment.*;
import environment.player.*;
import gui.*;

public class RobotSoccer
{	
	public static void main(String[] args)
	{		
		// set up logger
		final Logger log = Logger.getLogger(Player.class.getName());
		log.setLevel(Level.FINE);
		try
		{
			String name = "logs/" + "results";
			log.addHandler(new FileHandler(name));
			log.getHandlers()[0].setFormatter(new CustomFormatter());
		} catch (Exception e) {}
		
		// initiate pitch
		int width = 600;
		int height = 400;
		Pitch pitch = new Pitch(width, height);
		
		// add players and define their default positions
		ArrayList<Vector> startPositions = new ArrayList<Vector>();
		startPositions.add(new Vector(width - 80 + Math.random()*5, height/2 - 40 + Math.random()*5));
		startPositions.add(new Vector(width - 80 + Math.random()*5, height/2 + 40 + Math.random()*5));
		startPositions.add(new Vector(width - 80 + Math.random()*5, height/2 + Math.random()*5));
		startPositions.add(new Vector(80 + Math.random()*5, height/2 - 40 + Math.random()*5));
		startPositions.add(new Vector(80 + Math.random()*5, height/2 + 40 + Math.random()*5));
		startPositions.add(new Vector(80 + Math.random()*5, height/2 + Math.random()*5));
		ArrayList<Player> players = new ArrayList<Player>();
		players.add(new ImprPlayer(pitch, startPositions.get(0).clone(), Team.HOME));
		players.add(new ImprPlayer(pitch, startPositions.get(1).clone(), Team.HOME));
		players.add(new ImprPlayer(pitch, startPositions.get(2).clone(), Team.HOME));
		players.add(new StandardPlayer(pitch, startPositions.get(3).clone(), Team.AWAY));
		players.add(new StandardPlayer(pitch, startPositions.get(4).clone(), Team.AWAY));
		players.add(new StandardPlayer(pitch, startPositions.get(5).clone(), Team.AWAY));
		pitch.addPlayers(players, startPositions);
		
		// create GUI
		SimulationFrame frame = new SimulationFrame(width + 50, height + 50);
		frame.add(new PitchComponent(pitch));
		
		// start simulation
		simpleLoop(frame, pitch, log);
	}
	
	public static void simpleLoop(SimulationFrame frame, Pitch pitch, Logger log)
	{
		int roundcounter = 0;
		
		// record scores & setup experiments
		int numberOfGames = 5;
		int gameCounter = 1;
		int gameLength = 120000; // 2 min in ms
//		int gameLength = 3000;
		int[] totalGoals = new int[2];
		double[] averageNrOfGoalsPerGame = new double[2];
		int[] nrOfWins = new int[2];
		
		long start = System.currentTimeMillis();
		while(true)
		{
			// start new game if the time is up
			long now = System.currentTimeMillis();
			if (now - start > gameLength)
			{
				// gather statistics
				int[] score = pitch.getScore();
				totalGoals[0] += score[0];
				totalGoals[1] += score[1];
				averageNrOfGoalsPerGame[0] = 0.5 * averageNrOfGoalsPerGame[0] + 0.5 * score[0];
				averageNrOfGoalsPerGame[1] = 0.5 * averageNrOfGoalsPerGame[1] + 0.5 * score[1];
				if (score[0] != score[1])
				{
					if (score[0] < score[1]) nrOfWins[1]++;
					else nrOfWins[0]++;
				}
				
				// start new game
				start = System.currentTimeMillis();
				pitch.reset();
				roundcounter = 0;
				gameCounter++;
				System.out.println("start of game " + gameCounter);
				
				// break if all games are done
				if (gameCounter > numberOfGames) break;
			}
			
			System.out.println("---------------- Round " + roundcounter++ + " -----------------");
			pitch.update();
			frame.getComponent(0).repaint();
			try{
				Thread.sleep(20);
//				Thread.sleep(500);
			} catch (Exception exception) {}
		}
		
		log.fine(numberOfGames + " = number of games");
		log.fine(nrOfWins[0] + " = number of AWAY wins");
		log.fine(totalGoals[0] + " = total goals of AWAY team");
		log.fine(averageNrOfGoalsPerGame[0] + " = average number of goals of AWAY team");
		log.fine(nrOfWins[1] + " = number of HOME wins");
		log.fine(totalGoals[1] + " = total goals of HOME team");
		log.fine(averageNrOfGoalsPerGame[1] + " = average number of goals of HOME team");
	}
	
	public static void gameLoop2(SimulationFrame frame, Pitch pitch)
	{
		long ticksPerSecond = 24;
		long skipTicks = 1000 / ticksPerSecond;
		int maxFrameSkip = 10;
		
		long nextGameTick = System.currentTimeMillis();
		int loops;
		
		boolean gameIsRunning = true;
		while (gameIsRunning)
		{
			loops = 0;
			while (System.currentTimeMillis() > nextGameTick && loops < maxFrameSkip)
			{
				pitch.update();
				nextGameTick += skipTicks;
				loops++;
			}
			
//			frame.getComponent(0).repaint();
		}
	}
	
	public static void gameLoop1(SimulationFrame frame, Pitch pitch)
	{
		// initiate game loop
		long prev_frame_tick = 0;
		long curr_frame_tick = System.currentTimeMillis();
				
		boolean game_is_running = true;
		while (game_is_running)
		{
			prev_frame_tick = curr_frame_tick;
			curr_frame_tick = System.currentTimeMillis();
					
			//Pitch.update(curr_frame_tick - prev_frame_tick);
			frame.getComponent(0).repaint();
		}
	}
}
